package com.ultrasoft.farmasoft.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ultrasoft.farmasoft.domain.Pharmacystock;

@Repository(value = "pharmacyStockDao")
@Transactional(readOnly = false)
public class PharmacyStockDaoImpl implements PharmacyStockDao {
	private EntityManager em = null;
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	} 
	public List<Pharmacystock> getListPharmacyStock() {
		TypedQuery<Pharmacystock> q = em.createNamedQuery("Pharmacystock.findAll",Pharmacystock.class);
    	return q.getResultList();
	}

	public List<Pharmacystock> getListPharmacyStockByPharmacyId(Integer pharmacyId) {
		TypedQuery<Pharmacystock> q = em.createNamedQuery("Pharmacystock.findByPharmacyId",Pharmacystock.class);
    	q.setParameter("pharmacyId",pharmacyId);
    	return q.getResultList();
	}

	public List<Pharmacystock> getListPharmacyStockByStockId(Integer stockId) {
		TypedQuery<Pharmacystock> q = em.createNamedQuery("Pharmacystock.findByStockId",Pharmacystock.class);
    	q.setParameter("stockId",stockId);
    	return q.getResultList();
	}

	public Pharmacystock findByPharmacyIdByStockId(Integer pharmacyId,Integer stockId) {
		Pharmacystock res=null;
		TypedQuery<Pharmacystock> q = em.createNamedQuery("Pharmacystock.findByPharmacyIdByStockId",Pharmacystock.class);
    	q.setParameter("pharmacyId",pharmacyId);		
    	q.setParameter("stockId",stockId);
    	if(q.getResultList().size()==1)
    		res=(Pharmacystock)q.getSingleResult();
    	return res;
	}

	public void update(Pharmacystock pharmacyStock) {
		em.merge(pharmacyStock);
	} 
	
	public void remove(Pharmacystock pharmacyStock) {
		em.remove(findByPharmacyIdByStockId(pharmacyStock.getPharmacystockPK().getPharmacyId(),pharmacyStock.getPharmacystockPK().getStockId()));
	}
	
	public void add(Pharmacystock pharmacyStock) {
		em.persist(pharmacyStock);
	}
}
